<?php
namespace zake\app\help;

class Session{


    //
    private static $_cacheMap = [];


    /**
     * 所有登陆的用户
     *
     * @author liu.bin 2020-09-07 19:00
     */
    public static function all(){

        $all = [];
        $now = time();
        foreach (self::$_cacheMap as $value){

            $expire = true;
            if(!is_null($value)['expire']){
                $endTime    = $value['create_time'] + $value['expire'];
                $expire     = $now > $endTime ? false : true;
            }
            if(is_null($value['expire']) || $expire ){
                array_push($all,$value['value']);
            }
        }
        return $all;
    }



    /**
     *
     *
     * @author liu.bin 2020-09-04 15:25
     */
    public static function get($key,$default=null){

        if(!isset(self::$_cacheMap[$key])){
            return $default;
        }
        $cache = self::$_cacheMap[$key];


        if(is_null($cache['expire'])){
            return $cache['value'];
        }

        $endTime = $cache['create_time'] + $cache['expire'];
        if(time() <= $endTime){
            return $cache['value'];
        }

        return $default;
    }


    /**
     *
     * @param $key
     * @param $value
     * @param $expire
     *
     * @return bool
     * @author liu.bin 2020-09-04 15:27
     */
    public static function set($key,$value,$expire=null){

        $cache                  = [];
        $cache['create_time']   = time();
        $cache['expire']        = $expire;
        $cache['value']         = $value;
        self::$_cacheMap[$key] = $cache;
        return true;
    }


    /**
     *
     *
     * @author liu.bin 2020-09-04 15:39
     */
    public static function has($key){
        return isset(self::$_cacheMap[$key]) ? true : false;
    }


    /**
     *
     * @param $key
     *
     * @author liu.bin 2020-09-04 15:41
     */
    public static function clear($key){

        if(isset(self::$_cacheMap[$key])){
            self::$_cacheMap[$key] = null;
            unset(self::$_cacheMap[$key]);
        }
    }

}